import React, { useState } from 'react'
import { View, Text, Image } from '@tarojs/components'
import Taro from '@tarojs/taro';
import './index.scss';
import { $emit, getLocalStore, setLocalStore, showMes } from '../../utils/util'
import { UserInfo } from '../../utils/types'
const Avatar = () => {
  // 登录状态
  const [isLogin, setIsLogin] = useState<boolean>(() => getLocalStore('userInfo') ? true : false);
  // 用户信息
  const [userInfo, setUserInfo] = useState<{ imgSrc: string, nickName: string }>(() => {
    const { nickName = '', imgSrc = "https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132" } = getLocalStore<UserInfo>('userInfo');
    return {
      nickName,
      imgSrc
    }
  })

  // 获取用户信息
  const getUserInfo = async () => {
    // 头像信息
    try {
      const { userInfo } = await Taro.getUserProfile({ desc: '获取您的昵称、头像、地区及性别' })
      // 授权成功，存入store中
      setLocalStore('userInfo', { imgSrc: userInfo.avatarUrl, nickName: userInfo.nickName })
      // 改变userInfo
      setUserInfo({ imgSrc: userInfo.avatarUrl, nickName: userInfo.nickName })
      // 改变登录状态
      setIsLogin(true);

      // 通知状态哪里，修改动态
      $emit('signCb');
    } catch(e) {
      showMes('你已拒绝授权，可能会报名不了哦，请先授权哦')
    }


  }

  const { imgSrc, nickName } = userInfo;
  console.log(nickName);
  return (
    <View className="avatar fx-v-c">
      {
        isLogin ? (
          <>
            <Image className='a-img' src={imgSrc}></Image>
            <View className="name ofh" style={{maxWidth: '520rpx'}}>
              你好, {nickName}
            </View>
          </>
        ) : <>
            <Image className='a-img' src={imgSrc}></Image>
            <View className='login' onClick={getUserInfo}>授权登录</View>
          </>
      }
    </View>
  )
}

export default Avatar;
